package kr.saeildamil.project.secretary;

import java.util.ArrayList;

import kr.saeildamil.project.secretary.DB.DBHelper;
import kr.saeildamil.project.secretary.fragment.UserAdd;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class Setup extends Activity {
	TextView currentDate;
	String date;
	Button userDelete;
	DBHelper dbHelper;
	SQLiteDatabase db;
	Today today;
	FrameLayout frame;
	LinearLayout linear;
	ListView userlist;
	ListView deluserlist;
	CheckBox check;
	ToggleButton toggle;
	SlidingDrawer drawer;
	ArrayList<UserManager>arUserList;
	ArrayList<UserManager>arDelList;
	static String TAG="Setup";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Window win=getWindow();
		win.requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.setup);

		//findId
		currentDate=(TextView) findViewById(R.id.setup_current_date);
		frame=(FrameLayout) findViewById(R.id.deluser_frame);
		linear=(LinearLayout) findViewById(R.id.setup_linear2);
		userlist=(ListView) findViewById(R.id.userlist);
		deluserlist=(ListView) findViewById(R.id.deluserlist);
		drawer=(SlidingDrawer) findViewById(R.id.setup_slidingDrawer);

		today=new Today();
		date=today.currentdate2;
		currentDate.setText(date);

		GetuserDB();//등록된 사용자 불러오기

	}//end of onCreate
	public void mOnClick(View v){
		switch (v.getId()) {
		case R.id.setup_btn1://사용자추가,취소
			FragmentManager fm=getFragmentManager();
			Fragment fragment=fm.findFragmentById(R.id.useradd_frame);
			FragmentTransaction tr=fm.beginTransaction();
			UserAdd useradd=new UserAdd();
			if(fragment==null){
				drawer.animateClose();
				linear.setVisibility(View.INVISIBLE);
				tr.add(R.id.useradd_frame, useradd, "UserAdd");
				tr.commit();
			}else{
				linear.setVisibility(View.VISIBLE);
				tr.remove(fragment);
				tr.commit();
			}
			break;

		case R.id.setup_btn2://사용자 삭제
			if(frame.getVisibility()==View.INVISIBLE){
				linear.setVisibility(View.INVISIBLE);
				frame.setVisibility(View.VISIBLE);

				DeluserDB();

			}else{
				dbHelper=new DBHelper(this);
				db=dbHelper.getWritableDatabase();

				ArrayList<Integer> checked=new ArrayList<Integer>();
				Log.d(TAG, "arDelList.size"+String.valueOf(arDelList.size()));
				int listCount=deluserlist.getChildCount();
				for(int i=0; i<listCount; i++){
					check=(CheckBox) deluserlist.getChildAt(i).findViewById(R.id.userdel_check);
					if(check.isChecked()){
						checked.add(i);
						Log.d(TAG, "Checkedposition : "+i);
						Log.d(TAG, "arDelList.get(i).getId() : "+arDelList.get(i).getId());
						db.execSQL("DELETE FROM user WHERE _id='"+arDelList.get(i).getId()+"'");
					} 
				}
				dbHelper.close();
				startActivity(new Intent(this, Setup.class));
			}
			break;

		case R.id.setup_btn3://완료(메인화면 가기)
			Intent intent=new Intent(this, Main.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(intent);
			break;
		}
	}

	private void GetuserDB() {
		try {
			dbHelper=new DBHelper(this);
			db=dbHelper.getReadableDatabase();
			Cursor cursor;
			cursor=db.rawQuery("SELECT * FROM user", null);

			UserManager obj;
			arUserList=new ArrayList<UserManager>();
			while(cursor.moveToNext()){
				obj=new UserManager(cursor.getInt(0),cursor.getString(1),cursor.getString(2)
						,cursor.getString(3),cursor.getString(4),cursor.getString(5));
				arUserList.add(obj);
				/*Log.d(TAG, cursor.getInt(0)+cursor.getString(1)+cursor.getString(2)
						+cursor.getString(3)+cursor.getString(4)+cursor.getString(5));*/
			}
			startManagingCursor(cursor);

			SimpleCursorAdapter adapter=null;
			adapter=new SimpleCursorAdapter(this, R.layout.userlist, cursor, 
					new String[]{"date","name","occupation","age","gender"}, 
					new int[]{R.id.userlist_date,R.id.userlist_name,R.id.userlist_occupation,
					R.id.userlist_age,R.id.userlist_gender});	

			userlist.setAdapter(adapter);
			userlist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			userlist.setOnItemClickListener(userListener);

			//cursor.close();
			dbHelper.close();

		} catch (Exception e) {
			Toast.makeText(Setup.this, "사용자 정보를 입력하세요", 0).show();
		}
	}

	private void DeluserDB() {
		try {
			dbHelper=new DBHelper(this);
			db=dbHelper.getReadableDatabase();
			Cursor cursor;
			cursor=db.rawQuery("SELECT * FROM user", null);

			UserManager obj;
			arDelList=new ArrayList<UserManager>();
			while(cursor.moveToNext()){
				obj=new UserManager(cursor.getInt(0),cursor.getString(1),cursor.getString(2)
						,cursor.getString(3),cursor.getString(4),cursor.getString(5));
				arDelList.add(obj);
			}

			startManagingCursor(cursor);

			SimpleCursorAdapter adapter=null;
			adapter=new SimpleCursorAdapter(this, R.layout.userdel, cursor, 
					new String[]{"date","name","occupation","age","gender"}, 
					new int[]{R.id.userdel_date,R.id.userdel_name,R.id.userdel_occupation,
					R.id.userdel_age,R.id.userdel_gender});	

			deluserlist.setAdapter(adapter);
			deluserlist.setOnItemClickListener(delListener);


			//cursor.close();
			dbHelper.close();

		} catch (Exception e) {
			Toast.makeText(Setup.this, "사용자 정보를 입력하세요", 0).show();
		}

	}

	OnItemClickListener userListener=new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int position,
				long id) {
			toggle=(ToggleButton) userlist.getChildAt(position).findViewById(R.id.userlist_toggle);
			if(toggle.isChecked()){
				toggle.setChecked(false);
			}else{
				toggle.setChecked(true);
			}
		}
	};

	OnItemClickListener delListener=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int position,
				long arg3) {
			check=(CheckBox) userlist.getChildAt(position).findViewById(R.id.userdel_check);
			if(check.isChecked()){
				check.setChecked(false);
			}else{
				check.setChecked(true);
			}
		}
	};
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			AlertDialog.Builder dialog=new AlertDialog.Builder(this);
			dialog.setTitle("나비서");
			dialog.setMessage("프로그램을 종료하시겠습니까?");
			dialog.setIcon(R.drawable.ic_launcher);
			dialog.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					moveTaskToBack(true);
					finish();
				}
			});
			dialog.setNegativeButton("취소", null);
			dialog.show();
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

/*	@Override
	protected void onPause() {
		super.onPause();
		SharedPreferences pref=getSharedPreferences("Secretary", 0);
		SharedPreferences.Editor edit=pref.edit();

		int listCount=userlist.getCount();
		for(int i=0; i<listCount; i++){
			toggle=(ToggleButton) userlist.getChildAt(i).findViewById(R.id.userlist_toggle);
			if(toggle.isChecked()){
				edit.putString("Selecteduser",arUserList.get(i).getName());
				Log.d(TAG, "Selecteduser : "+arUserList.get(i).getName());
			}
			if(toggle.isChecked()){
				edit.putBoolean(arUserList.get(i).getName(), toggle.isChecked());
				edit.putString(String.valueOf(arUserList.get(i).getId()), arUserList.get(i).getName());
				Log.d(TAG, arUserList.get(i).getName());
			}
		}
		edit.putInt("usercount", listCount);
		Log.d(TAG, "userlist : "+listCount);
		edit.commit();
	}*/
}//end of Setup Class
